/**
 * kl yy-ds @2021
 */
package com.cxps.server.type.controller;

import com.cxps.cloud.message.ApiResponse;
import com.cxps.server.type.domain.ProductType;
import com.cxps.server.type.domain.ProductTypeQuery;
import com.cxps.server.type.service.ProductTypeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

/**
 * 商品类型控制层
 *
 * @author YouCai.Liu
 * @since 2021/11/1
 * ...
 */
@Slf4j
@RestController
@RequestMapping("/product")
@Api(tags = "商品类型API")
public class ProductTypeController {

    @Autowired
    private ProductTypeService productTypeService;

    /**
     * 商品分类列表
     *
     * @return
     */
    @PostMapping("/typeList")
    @ApiOperation(value = "商品分类列表", response = ApiResponse.class)
    public ApiResponse list(@RequestBody ProductTypeQuery query) {
        return ApiResponse.fireSuccess(productTypeService.list(query));
    }

    /**
     * 商品分类添加
     *
     * @return
     */
    @PostMapping("/typeAdd")
    @ApiOperation(value = "商品分类添加", response = ApiResponse.class)
    public ApiResponse add(@RequestBody ProductType productType) {
        productTypeService.add(productType);
        productTypeService.updateCache();
        return ApiResponse.fireSuccess();
    }

    /**
     * 商品分类修改
     *
     * @return
     */
    @PostMapping("/typeUpdate")
    @ApiOperation(value = "商品分类修改", response = ApiResponse.class)
    public ApiResponse update(@RequestBody ProductType productType) {
        try {
            Assert.hasLength(productType.getId(), "ID不能为空");
            productTypeService.update(productType);
            return ApiResponse.fireSuccess();
        } catch (IllegalArgumentException e) {
            return ApiResponse.fireSuccess(e.getMessage());
        }
    }

    /**
     * 根据ID查询商品分类
     *
     * @param id
     * @return
     */
    @GetMapping("/type/{id}")
    @ApiOperation(value = "根据ID查询商品分类", response = ApiResponse.class)
    public ApiResponse get(@PathVariable String id) {
        return ApiResponse.fireSuccess(productTypeService.get(id));
    }

    /**
     * 根据ID删除商品分类
     *
     * @param id
     * @return
     */
    @GetMapping("/typeDel/{id}")
    @ApiOperation(value = "根据ID删除商品分类", response = ApiResponse.class)
    public ApiResponse del(@PathVariable String id) {
        try {
            productTypeService.del(id);
            return ApiResponse.fireSuccess();
        } catch (Exception e) {
            return ApiResponse.fireError(e.getMessage());
        }
    }

    /**
     * 商品分类树形数据
     *
     * @return
     */
    @PostMapping("/typeTree")
    @ApiOperation(value = "商品分类树形数据", response = ApiResponse.class)
    public ApiResponse typeTree() {
        return ApiResponse.fireSuccess(productTypeService.typeTree());
    }

}
